<template>
  <view class="quality-management-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-purple" :isBack="true">
      <block slot="content">质量管理</block>
      <block slot="right">
        <text class="cuIcon-add" @click="createQualityCheck"></text>
      </block>
    </cu-custom>

    <!-- 统计概览 -->
    <view class="stats-overview margin-top bg-white">
      <view class="stats-grid padding">
        <view class="stat-item" @click="filterByStatus('all')">
          <view class="stat-number text-purple">{{ qualityStats.total }}</view>
          <view class="stat-label">总检查</view>
        </view>
        <view class="stat-item" @click="filterByStatus('passed')">
          <view class="stat-number text-green">{{ qualityStats.passed }}</view>
          <view class="stat-label">合格</view>
        </view>
        <view class="stat-item" @click="filterByStatus('failed')">
          <view class="stat-number text-red">{{ qualityStats.failed }}</view>
          <view class="stat-label">不合格</view>
        </view>
        <view class="stat-item" @click="filterByStatus('pending')">
          <view class="stat-number text-orange">{{ qualityStats.pending }}</view>
          <view class="stat-label">待检查</view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-filter margin-top bg-white">
      <view class="search-bar padding">
        <view class="search-input-wrapper">
          <input v-model="searchKeyword" 
                 placeholder="搜索产品名称或批次号" 
                 class="search-input" 
                 @input="onSearch" />
          <text class="cuIcon-search search-icon"></text>
        </view>
      </view>
      <view class="filter-tabs padding-lr">
        <scroll-view scroll-x class="filter-scroll">
          <view class="filter-tab-list">
            <view v-for="tab in filterTabs" :key="tab.value"
                  class="filter-tab" 
                  :class="{ active: currentFilter === tab.value }"
                  @click="changeFilter(tab.value)">
              {{ tab.label }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 质检列表 -->
    <view class="quality-list margin-top">
      <view v-for="quality in filteredQualities" :key="quality.id" 
            class="quality-item bg-white margin-bottom" 
            @click="viewQualityDetail(quality)">
        <view class="quality-header padding">
          <view class="flex justify-between align-center">
            <view class="quality-title">{{ quality.productName }}</view>
            <view class="quality-result" :class="quality.resultClass">
              {{ quality.resultText }}
            </view>
          </view>
          <view class="quality-meta margin-top-sm">
            <text class="text-sm text-gray">批次：{{ quality.batchNo }}</text>
            <text class="text-sm text-gray margin-left">检查项：{{ quality.checkItems.length }}项</text>
          </view>
        </view>
        
        <view class="quality-content padding-lr">
          <view class="quality-progress margin-bottom-sm">
            <view class="flex justify-between align-center margin-bottom-xs">
              <text class="text-sm">检查进度</text>
              <text class="text-sm">{{ quality.completedItems }}/{{ quality.totalItems }}</text>
            </view>
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: quality.progress + '%' }"></view>
            </view>
          </view>
          
          <view class="quality-inspector flex align-center margin-bottom-sm">
            <text class="text-sm text-gray">检查员：</text>
            <image v-if="quality.inspector" 
                   :src="quality.inspector.avatar || '/static/images/default-avatar.png'" 
                   class="inspector-avatar margin-left-xs"></image>
            <text class="text-sm margin-left-xs">{{ (quality.inspector && quality.inspector.name) || '未分配' }}</text>
          </view>
          
          <view class="quality-metrics flex justify-between margin-bottom-sm">
            <view class="metric-item">
              <text class="metric-label text-sm text-gray">合格率</text>
              <text class="metric-value text-sm text-green">{{ quality.passRate }}%</text>
            </view>
            <view class="metric-item">
              <text class="metric-label text-sm text-gray">检查时间</text>
              <text class="metric-value text-sm">{{ quality.checkDuration }}min</text>
            </view>
            <view class="metric-item">
              <text class="metric-label text-sm text-gray">问题数</text>
              <text class="metric-value text-sm text-red">{{ quality.issueCount }}</text>
            </view>
          </view>
          
          <view class="quality-time flex justify-between text-sm text-gray">
            <text>创建时间：{{ formatTime(quality.createTime) }}</text>
            <text v-if="quality.completeTime">完成时间：{{ formatTime(quality.completeTime) }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="quality-actions padding">
          <view class="action-buttons flex gap-sm">
            <button v-if="quality.status === 'pending'" 
                    class="cu-btn sm bg-blue" 
                    @click.stop="startCheck(quality)">
              开始检查
            </button>
            <button v-if="quality.status === 'checking'" 
                    class="cu-btn sm bg-green" 
                    @click.stop="continueCheck(quality)">
              继续检查
            </button>
            <button v-if="quality.status === 'completed'" 
                    class="cu-btn sm bg-purple" 
                    @click.stop="viewReport(quality)">
              查看报告
            </button>
            <button class="cu-btn sm bg-gray line" 
                    @click.stop="editQuality(quality)">
              编辑
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredQualities.length === 0" class="empty-state text-center padding">
      <text class="cuIcon-check text-gray" style="font-size: 120rpx;"></text>
      <view class="text-gray margin-top">暂无质检记录</view>
    </view>

    <!-- 快速检查弹窗 -->
    <view v-if="showQuickCheckModal" class="quick-check-modal" @click="showQuickCheckModal = false">
      <view class="quick-check-content" @click.stop>
        <view class="quick-check-header padding">
          <text class="text-lg text-bold">快速质检</text>
          <text class="cuIcon-close float-right" @click="showQuickCheckModal = false"></text>
        </view>
        <view class="quick-check-form padding">
          <view class="form-item margin-bottom">
            <text class="form-label">产品名称：</text>
            <input v-model="quickCheckForm.productName" 
                   placeholder="请输入产品名称" 
                   class="form-input" />
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">批次号：</text>
            <input v-model="quickCheckForm.batchNo" 
                   placeholder="请输入批次号" 
                   class="form-input" />
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">检查类型：</text>
            <picker :range="checkTypeOptions" 
                    :value="quickCheckForm.checkTypeIndex"
                    @change="onCheckTypeChange">
              <view class="form-picker">
                {{ quickCheckForm.checkType || '请选择检查类型' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">检查标准：</text>
            <textarea v-model="quickCheckForm.standard" 
                      placeholder="请输入检查标准" 
                      class="form-textarea"></textarea>
          </view>
        </view>
        <view class="quick-check-actions padding">
          <button class="cu-btn bg-gray margin-right" @click="showQuickCheckModal = false">取消</button>
          <button class="cu-btn bg-purple" @click="confirmQuickCheck">创建检查</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      searchKeyword: '',
      currentFilter: 'all',
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '待检查', value: 'pending' },
        { label: '检查中', value: 'checking' },
        { label: '已完成', value: 'completed' },
        { label: '合格', value: 'passed' },
        { label: '不合格', value: 'failed' }
      ],
      qualityStats: {
        total: 0,
        passed: 0,
        failed: 0,
        pending: 0
      },
      qualities: [],
      filteredQualities: [],
      showQuickCheckModal: false,
      quickCheckForm: {
        productName: '',
        batchNo: '',
        checkType: '',
        checkTypeIndex: 0,
        standard: ''
      },
      checkTypeOptions: ['外观检查', '尺寸检查', '功能检查', '性能检查', '安全检查']
    }
  },

  onLoad() {
    this.loadQualities()
  },

  onPullDownRefresh() {
    this.loadQualities().then(() => {
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    async loadQualities() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await mesApi.quality.getList()
        this.qualities = response.data.map(quality => ({
          ...quality,
          resultClass: this.calculateResultClass(quality.result),
          resultText: this.calculateResultText(quality.result),
          progress: this.calculateProgress(quality.completedItems, quality.totalItems)
        }))
        
        this.calculateStats()
        this.filterQualities()
        
      } catch (error) {
        console.error('加载质检失败:', error)
        this.loadMockData()
      } finally {
        uni.hideLoading()
      }
    },

    loadMockData() {
      this.qualities = [
        {
          id: 1,
          productName: '铝合金门框',
          batchNo: 'B20240301001',
          status: 'completed',
          result: 'passed',
          checkItems: [
            { name: '外观检查', status: 'passed' },
            { name: '尺寸检查', status: 'passed' },
            { name: '功能检查', status: 'passed' }
          ],
          completedItems: 3,
          totalItems: 3,
          inspector: {
            id: 1,
            name: '张三',
            avatar: ''
          },
          passRate: 100,
          checkDuration: 45,
          issueCount: 0,
          createTime: '2024-03-01 09:00:00',
          completeTime: '2024-03-01 09:45:00',
          resultClass: 'result-passed',
          resultText: '合格',
          progress: 100
        },
        {
          id: 2,
          productName: '塑钢窗扇',
          batchNo: 'B20240301002',
          status: 'checking',
          result: 'pending',
          checkItems: [
            { name: '外观检查', status: 'passed' },
            { name: '尺寸检查', status: 'checking' },
            { name: '密封检查', status: 'pending' }
          ],
          completedItems: 1,
          totalItems: 3,
          inspector: {
            id: 2,
            name: '李四',
            avatar: ''
          },
          passRate: 50,
          checkDuration: 20,
          issueCount: 1,
          createTime: '2024-03-01 10:00:00',
          completeTime: null,
          resultClass: 'result-pending',
          resultText: '检查中',
          progress: 33
        }
      ]
      
      this.calculateStats()
      this.filterQualities()
    },

    calculateStats() {
      this.qualityStats = {
        total: this.qualities.length,
        passed: this.qualities.filter(q => q.result === 'passed').length,
        failed: this.qualities.filter(q => q.result === 'failed').length,
        pending: this.qualities.filter(q => q.status === 'pending').length
      }
    },

    calculateResultClass(result) {
      const resultMap = {
        'passed': 'result-passed',
        'failed': 'result-failed',
        'pending': 'result-pending'
      }
      return resultMap[result] || 'result-pending'
    },

    calculateResultText(result) {
      const resultMap = {
        'passed': '合格',
        'failed': '不合格',
        'pending': '检查中'
      }
      return resultMap[result] || '检查中'
    },

    calculateProgress(completed, total) {
      return total > 0 ? Math.round((completed / total) * 100) : 0
    },

    onSearch() {
      this.filterQualities()
    },

    changeFilter(filter) {
      this.currentFilter = filter
      this.filterQualities()
    },

    filterByStatus(status) {
      this.currentFilter = status
      this.filterQualities()
    },

    filterQualities() {
      let filtered = this.qualities

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(quality => 
          quality.productName.toLowerCase().includes(keyword) ||
          quality.batchNo.toLowerCase().includes(keyword)
        )
      }

      // 状态过滤
      if (this.currentFilter !== 'all') {
        if (this.currentFilter === 'passed' || this.currentFilter === 'failed') {
          filtered = filtered.filter(quality => quality.result === this.currentFilter)
        } else {
          filtered = filtered.filter(quality => quality.status === this.currentFilter)
        }
      }

      this.filteredQualities = filtered
    },

    viewQualityDetail(quality) {
      uni.navigateTo({
        url: `/pages/production/quality/detail?id=${quality.id}`
      })
    },

    createQualityCheck() {
      this.quickCheckForm = {
        productName: '',
        batchNo: '',
        checkType: '',
        checkTypeIndex: 0,
        standard: ''
      }
      this.showQuickCheckModal = true
    },

    startCheck(quality) {
      uni.navigateTo({
        url: `/pages/production/quality/check?id=${quality.id}`
      })
    },

    continueCheck(quality) {
      uni.navigateTo({
        url: `/pages/production/quality/check?id=${quality.id}`
      })
    },

    viewReport(quality) {
      uni.navigateTo({
        url: `/pages/production/quality/report?id=${quality.id}`
      })
    },

    editQuality(quality) {
      uni.navigateTo({
        url: `/pages/production/quality/edit?id=${quality.id}`
      })
    },

    onCheckTypeChange(e) {
      this.quickCheckForm.checkTypeIndex = e.detail.value
      this.quickCheckForm.checkType = this.checkTypeOptions[e.detail.value]
    },

    async confirmQuickCheck() {
      if (!this.quickCheckForm.productName.trim()) {
        uni.showToast({
          title: '请输入产品名称',
          icon: 'none'
        })
        return
      }

      if (!this.quickCheckForm.batchNo.trim()) {
        uni.showToast({
          title: '请输入批次号',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '创建中...' })
        
        await mesApi.quality.create(this.quickCheckForm)
        
        uni.showToast({
          title: '创建成功',
          icon: 'success'
        })
        
        this.showQuickCheckModal = false
        this.loadQualities()
        
      } catch (error) {
        console.error('创建失败:', error)
        uni.showToast({
          title: '创建失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    formatTime(timeStr) {
      if (!timeStr) return '--'
      const date = new Date(timeStr)
      return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.quality-management-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.stats-overview {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.search-filter {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .search-input-wrapper {
    position: relative;
    
    .search-input {
      width: 100%;
      height: 80rpx;
      padding: 0 60rpx 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .search-icon {
      position: absolute;
      right: 24rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }
  }
  
  .filter-scroll {
    white-space: nowrap;
    
    .filter-tab-list {
      display: inline-flex;
      
      .filter-tab {
        padding: 16rpx 24rpx;
        margin-right: 16rpx;
        border-radius: 20rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        white-space: nowrap;
        
        &.active {
          background-color: #1890ff;
          color: white;
        }
      }
    }
  }
}

.quality-list {
  margin: 0 24rpx;
  
  .quality-item {
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .quality-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .quality-result {
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;
      
      &.result-passed {
        background-color: #f6ffed;
        color: #52c41a;
      }
      
      &.result-failed {
        background-color: #fff1f0;
        color: #f5222d;
      }
      
      &.result-pending {
        background-color: #e6f7ff;
        color: #1890ff;
      }
    }
    
    .progress-bar {
      height: 8rpx;
      background-color: #f0f0f0;
      border-radius: 4rpx;
      overflow: hidden;
      
      .progress-fill {
        height: 100%;
        background-color: #722ed1;
        transition: width 0.3s ease;
      }
    }
    
    .inspector-avatar {
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
    }
    
    .quality-metrics {
      .metric-item {
        text-align: center;
        
        .metric-label {
          display: block;
          margin-bottom: 4rpx;
        }
        
        .metric-value {
          font-weight: bold;
        }
      }
    }
    
    .action-buttons {
      .cu-btn {
        flex: 1;
        margin-right: 16rpx;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

.quick-check-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .quick-check-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;
    
    .quick-check-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;
      
      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .quick-check-form {
      max-height: 60vh;
      overflow-y: auto;
      
      .form-item {
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 16rpx;
        }
        
        .form-input {
          width: 100%;
          height: 80rpx;
          padding: 0 24rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
        }
        
        .form-textarea {
          width: 100%;
          min-height: 120rpx;
          padding: 16rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
          resize: none;
        }
        
        .form-picker {
          height: 80rpx;
          padding: 0 24rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #333;
        }
      }
    }
    
    .quick-check-actions {
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      gap: 16rpx;
      
      .cu-btn {
        flex: 1;
      }
    }
  }
}

.empty-state {
  margin-top: 120rpx;
}
</style>
